package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.MsgDetailsActivity;
import com.mingtu.jgspatrol.adapter.MsgNoticeAdapter;
import com.mingtu.jgspatrol.bean.MyMessageBean;
import com.mingtu.jgspatrol.databinding.FragmentMsgNoticeBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

public class MsgNoticeFragment extends BaseBindingFragment<FragmentMsgNoticeBinding> implements LazyFragmentPagerAdapter.Laziable {
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private MsgNoticeAdapter msgNoticeAdapter;
    private int clickPosition = -1;

    public static MsgNoticeFragment getInstance() {
        MsgNoticeFragment ef = new MsgNoticeFragment();
        return ef;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_msg_notice;
    }

    @Override
    protected void initData() {
        getNoticeList(1);
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager);
//        binding.recycler.addItemDecoration(MyUtills.getRecyclerViewDivider(context, R.drawable.shape_dive_line));
        binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());

        msgNoticeAdapter = new MsgNoticeAdapter();
        if (isOpenLoadAnimation) {
            msgNoticeAdapter.isFirstOnly(isFirstOnly);
            msgNoticeAdapter.openLoadAnimation(animationType);
        }
        msgNoticeAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(msgNoticeAdapter);
        msgNoticeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                clickPosition = position;
                MyMessageBean.PageBean.RecordsBean bean = msgNoticeAdapter.getData().get(position);
                int status = bean.getStatus();
                if (status == 0) {
                    //将状态设置为已读
                    bean.setStatus(1);
                    msgNoticeAdapter.getData().set(position, bean);
                }

                int id = bean.getId();
                String content = bean.getMsgContent();
                String title = bean.getMsgType();
                String time = bean.getCreateTime();

                Intent intent = new Intent(getActivity(), MsgDetailsActivity.class);
                intent.putExtra("id", id + "");
                intent.putExtra("detail", content);
                intent.putExtra("title", title);
                intent.putExtra("time", time);
                startActivityForResult(intent, 100);
            }
        });

    }

    @Override
    protected void getData() {
        initListener();
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                clickPosition = -1;
                getNoticeList(1);

            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(msgNoticeAdapter.getData(), Constant.PAGE_SIZE);
                    getNoticeList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 获取消息列表
     *
     * @param pageNum
     */
    private void getNoticeList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_MY_MESSAGE_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MyMessageBean messageBean = new MyMessageBean();
                                messageBean = gson.fromJson(result, MyMessageBean.class);
                                List<MyMessageBean.PageBean.RecordsBean> dataBeans = messageBean.getPage().getRecords();
                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            msgNoticeAdapter.replaceData(dataBeans);
                                        } else {
                                            msgNoticeAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            msgNoticeAdapter.notifyItemChanged(clickPosition);
        }
    }
}